<template>
  <div>
    <el-dialog :visible.sync="visible"
               :title="title"
               width="80%"
               :before-close="modalClose"
               center
               :close-on-click-modal="false"
               :close-on-press-escape="false">
      <el-form :model="addForm"
               ref="addFormRef"
               :rules="addRules"
               label-width="100px">
        <el-form-item label="试纸名称:"
                      prop="testStripId">
          <el-select v-model="addForm.testStripId"
                     placeholder="请选择试纸名称"
                     filterable
                     remote
                     reserve-keyword
                     clearable
                     :remote-method="(query) => {remoteMethod(query, 'testStripName')}"
                     :loading="loading1"
                     class="w-200"
                     @change="val=>handleSelect(val, 'testStripName')">
            <el-option v-for="item in testStripFilterList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>

        </el-form-item>
        <el-form-item label="厂家名称:"
                      prop="factoryId">
          <el-select v-model="addForm.factoryId"
                     placeholder="请选择厂家名称"
                     :disabled="isDisabled"
                     @change="testStripFactory">
            <el-option :label="item.factoryName"
                       v-for="item in testStripFactoryList"
                       :key="item.factoryId"
                       :value="item.factoryId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试纸批号:"
                      prop="batchId">
          <el-select v-model="addForm.batchId"
                     placeholder="请选择试纸批号"
                     class="w-300"
                     :disabled="isDisabled">
            <el-option
              v-for="item in batchList"
              :key="item.batchId"
              :label="item.batchNumber"
              :value="item.batchId">
              <span style="float: left">{{ item.batchNumber }}</span>
              <span style="float: right;">{{ item.barcode }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单数量:">
          <el-table border
                    :data="tableData">
            <el-table-column label="试纸规格"
                             prop="standardNum"
                             align="center">
              <template slot-scope="scope">
                <el-input class="w-200"
                          placeholder="请输入试纸数量"
                          v-model="scope.row.standardNum"
                          :disabled="codeList.length > 0 ? true : false"></el-input>
                <el-select v-model="scope.row.standardUnit"
                           placeholder="请选择规格单位"
                           class="w-200"
                           :disabled="codeList.length > 0 ? true : false">
                  <el-option :label="item.standardUnit"
                             v-for="item in standardUnitList"
                             :key="item.id"
                             :value="item.standardUnit"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="包装单位"
                             align="center"
                             prop="packageNum">
              <template slot-scope="scope">
                <el-input class="w-200"
                          placeholder="请输入包装数量"
                          v-model="scope.row.packageNum"
                          :disabled="codeList.length > 0 ? true : false"></el-input>
                <el-select v-model="scope.row.packageUnit"
                           placeholder="请选择包装单位"
                           class="w-200"
                           :disabled="codeList.length > 0 ? true : false">
                  <el-option :label="item.packageUnit"
                             v-for="item in packageUnitList"
                             :key="item.id"
                             :value="item.packageUnit"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="下单数量"
                             align="center"
                             prop="num">
              <template slot-scope="scope">
                <el-input class="w-200"
                          placeholder="请输入下单数量"
                          v-model="scope.row.num"
                          :disabled="codeList.length > 0 ? true : false"></el-input>
                <el-select v-model="scope.row.numUnit"
                           placeholder="请选择包装单位"
                           class="w-200"
                           :disabled="codeList.length > 0 ? true : false">
                  <el-option :label="item.numUnit"
                             v-for="item in numUnitList"
                             :key="item.id"
                             :value="item.numUnit"></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="code码:"
                      v-if="isShowCodeMod">
          <el-card>
            <el-row>
              <el-col :span="10">
                <!-- :limit="limitNum" -->
                <el-upload :action="fileImportAction"
                           :data="{'testStripOrderId': currId}"
                           :disabled="!isDisabled"
                           :on-success="handleAvatarSuccess"
                           accept=".xls,.xlsx"
                           :auto-upload="true"
                           :on-exceed="exceedFile"
                           limit="1"
                           :before-upload="beforeAvatarUpload"
                           @clearFiles="clearUploadFiles">
                  <el-button type="primary"
                             :disabled="!codeObj">
                    导入code码
                  </el-button>
                </el-upload>
              </el-col>
              <el-col :span="3">
                <el-button type="primary"
                           @click="exportExcel"
                           :disabled="!isDisabled && !codeList.length > 0">导出code码
                </el-button>
              </el-col>
            </el-row>

            <el-divider></el-divider>
            <el-tag type="info"
                    v-for="item in codeList"
                    :key="item.id"
                    class="mb-20 mr-20">
              {{ item.code }}
            </el-tag>
          </el-card>
        </el-form-item>
        <p align="center">
          <el-button @click="modalClose"
                     v-if="isDetail">取消
          </el-button>
          <el-button type="primary"
                     v-else
                     @click="modalClose">返回
          </el-button>
          <el-button type="primary"
                     v-if="!isDetail"
                     @click="submitForm(addForm, isSubmitType)">保存
          </el-button>
        </p>
      </el-form>

    </el-dialog>
  </div>
</template>
<script>

export default {
  name: 'codeDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    codeObj: {
      type: Object,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      loading1: false,
      title: '',
      isSubmitType: 'add',
      testStripList: [], // 试纸名称列表
      testStripFilterList: [],
      testStripFactoryList: [], // 厂家名称
      batchList: [], // 试纸批号列表
      standardUnitList: [
        {id: 1, standardUnit: '条/筒'},
        {id: 2, standardUnit: '人份/盒'}
      ],
      packageUnitList: [
        {id: 1, packageUnit: '筒/盒'},
        {id: 2, packageUnit: '盒'}
      ],
      numUnitList: [
        {id: 1, numUnit: '盒'}
      ],
      addForm: {
        testStripId: '',
        factoryId: '',
        batchId: ''
      },
      addRules: {
        testStripId: [
          {required: true, message: '请选择试纸名称', trigger: 'change'}
        ],
        factoryId: [
          {required: true, message: '请选择厂家名称', trigger: 'change'}
        ],
        batchId: [
          {required: true, message: '请选择试纸批号', trigger: 'change'}
        ]
      },
      tableData: [
        {
          standardNum: '', // 规格数量
          standardUnit: '', // 规格单位
          packageNum: '', // 包装数量
          packageUnit: '', // 包装单位
          num: '', // 下单数量
          numUnit: '', // 数量单位
        }
      ],
      currId: '',
      codeList: [], // code码
      isDisabled: false,
      isShowCodeMod: false, // 是否显示code码
      fileImportAction: this.api.testStrip.importTestStripCode,
      limitNum: 1,  // 上传excell时，同时允许上传的最大数
    }
  },
  methods: {
    // 关闭弹出框
    modalClose() {
      this.$emit('update:visible', false); // 直接修改父组件的属性
    },
    // 提交保存
    submitForm(form, isSubmitType) {
      if (isSubmitType === 'add') {
        /* let factoryObj = this.testStripFactoryList.find(item => item.id === this.addForm.factoryId)
        this.addForm.factoryId = factoryObj.factoryId */
        let target = {};
        this.tableData.forEach(item => {
          const source = JSON.parse(`{"standardNum":"${item.standardNum}","standardUnit":"${item.standardUnit}","packageNum":"${item.packageNum}","packageUnit":"${item.packageUnit}","num":"${item.num}","numUnit":"${item.numUnit}"}`); // 利用JSON.parse将对象格式直接造出来
          Object.assign(target, source);
        })
        let params = {
          id: this.currId,
          ...form,
          ...target
        }
        this.$refs.addFormRef.validate(async (valid) => {
          if (valid) {
            let res = this.tableData
            if (res.length > 0) {
              let res = this.tableData
              let item = res[res.length - 1]
              if (item.standardNum === '') {
                this.$message.error('请输入试纸数量');
                return
              }
              if (item.standardUnit === '') {
                this.$message.error('请选择规格单位');
                return
              }
              if (item.packageNum === '') {
                this.$message.error('请输入包装数量');
                return
              }
              if (item.packageUnit === '') {
                this.$message.error('请选择包装单位');
                return
              }
              if (item.num === '') {
                this.$message.error('请输入下单数量');
                return
              }
              if (item.numUnit === '') {
                this.$message.error('请选择包装单位');
                return
              }
            }
            const {data: result} = await this.post(this.api.testStrip.updateOrderManager, params)
            if (result.code === '200') {
              this.$message.success('保存成功!');
              this.$parent.getList();
              this.modalClose();
            }
          }
        })
      }
      if (isSubmitType === 'edit') {
        let target = {};
        this.tableData.forEach(item => {
          const source = JSON.parse(`{"standardNum":"${item.standardNum}","standardUnit":"${item.standardUnit}","packageNum":"${item.packageNum}","packageUnit":"${item.packageUnit}","num":"${item.num}","numUnit":"${item.numUnit}"}`); // 利用JSON.parse将对象格式直接造出来
          Object.assign(target, source);
        })
        let params = {
          id: this.currId,
          ...form,
          ...target
        }
        console.log(params)
        // return
        this.$refs.addFormRef.validate(async (valid) => {
          if (valid) {
            const {data: resData} = await this.post(this.api.testStrip.updateOrderManager, params)
            if (resData.code === '200') {
              this.$message.success('保存成功!');
              this.$parent.getList(); // 调用父组件列表方法
              this.modalClose();
            }
          }
        })
      }
    },

    // 查询详情
    getDetails() {
      this.post(this.api.testStrip.getTestStripOrderDetail, {
        id: this.currId
      })
        .then(({data: res}) => {
          if (res.code === '200') {
            let resData = res.object
            this.addForm = resData;
            // 回显试纸名称
            this.addForm.testStripId = resData.testStripId;
            this.testStripFilterList = [
              {id: resData.testStripId, name: resData.testStripName}
            ];
            // 回显厂家名称
            this.addForm.factoryId = resData.factoryId;
            this.testStripFactoryList = [{
              factoryId: resData.factoryId,
              factoryName: resData.factoryName,
            }];
            // 试纸批号
            this.addForm.batchId = resData.batchId;
            this.batchList = [{
              batchId: resData.batchId,
              batchNumber: resData.batchNumber,
              barcode: resData.barcode,
            }];

            let {standardNum, standardUnit, packageNum, packageUnit, num, numUnit} = resData;
            this.tableData[0].standardNum = standardNum;
            this.tableData[0].standardUnit = standardUnit;
            this.tableData[0].packageNum = packageNum;
            this.tableData[0].packageUnit = packageUnit;
            this.tableData[0].num = num;
            this.tableData[0].numUnit = numUnit;
          }
        })
    },
    // 远程搜索
    remoteMethod(query, type) {
      if (query !== '') {
        let _this = this;
        if (query) {
          if (type === 'testStripName') { // 试纸名称
            _this.loading1 = true;
            this.post(this.api.testStrip.getTestStripAndFactoryInfo, {
              name: query
            }).then(res => {
              if (res.data.code === '200') {
                _this.loading1 = false;
                _this.testStripList = res.data.object.map(({
                                                             id,
                                                             name,
                                                             testStripFactoryDtos
                                                           }) => ({
                  id,
                  name,
                  testStripId: id,
                  testStripName: name,
                  testStripFactoryDtos
                }))

              }
            })
            _this.loading1 = false;
            _this.testStripFilterList = _this.testStripList.filter(item => item.name.indexOf(query) > -1);
          }

        }
      } else {
        if (type === 'testStripName') {
          this.testStripFilterList = [];
        }

      }
    },
    // 选择试纸名称
    handleSelect(item, type) {
      if (type === 'testStripName') {
        this.addForm.testStripId = item;
        let res = [];
        this.testStripFilterList.map(el => {
          if (el.id === item) {
            res = el.testStripFactoryDtos;
          }
        })
        this.testStripFactoryList = res;
      }
    },
    // 查询试纸厂商信息
    getTestStripAndFactoryInfo() {
      this.post(this.api.testStrip.getTestStripAndFactoryInfo)
        .then(({data: res}) => {
          if (res.code === '200') {
            this.testStripList = res.object.map(({
                                                   id,
                                                   name,
                                                   testStripFactoryDtos
                                                 }) => ({
              id,
              name,
              testStripId: id,
              testStripName: name,
              testStripFactoryDtos
            }))
          }
        })

    },
    // 选择试厂家名称
    testStripFactory(val) {
      let strObj = this.testStripFactoryList.find(v => v.factoryId === val);
      this.post(this.api.testStrip.getTestStripBatch, {
        testStripId: this.addForm.testStripId,
        testStripFactoryId: strObj.id
      }).then(({data: res}) => {
        if (res.code === '200') {
          this.batchList = res.object.map(({
                                             id,
                                             batchNumber,
                                             barcode
                                           }) => ({
            batchId: id,
            batchNumber,
            barcode
          }))
        }
      })

    },
    // 获取code码信息
    getTestStripCode() {
      this.post(this.api.testStrip.getTestStripCode, {
        testStripOrderId: this.currId
      }).then(({data: res}) => {
        if (res.code === '200') {
          this.codeList = res.object;
        }
      })

    },
    // 导出
    exportExcel() {
      let url = this.api.testStrip.exportTestStripCode;
      this.commonFunction.exportFileData({testStripOrderId: this.currId}, url, this.codeObj.testStripName + '试纸订单code编码', '.xlsx');
    },
    // 导入文件成功
    handleAvatarSuccess(response, file, fileList) {
      if (response.code === '200') {
        this.codeList = response.object;
        this.message.success('导入成功');
      } else {
        // 状态码不是200时上传失败 从列表中删除
        fileList.splice(fileList.indexOf(file), 1);
        this.$message.error(response.message);
      }
      ;
    },
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      // this.$message.warning(`只能选择 ${this.limitNum} 个文件!`);
    },
    clearUploadFiles(val) {
      console.log(val)
    },
    // 文件导入格式限制
    beforeAvatarUpload(file) {
      const isType = file.type === 'application/vnd.ms-excel';
      const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      const fileType = isType || isTypeComputer;
      if (!fileType) {
        this.$message.error('上传文件只能是xls/xlsx格式！');
      }
      return fileType;
    }

  },
  created() {
    if (this.codeObj) {
      this.currId = this.codeObj.id;
      this.getDetails(); // 详情
      this.getTestStripCode();// 获取code码信息
      this.isShowCodeMod = true;
      if (this.isDetail) {
        this.isDisabled = true
        this.title = '详 情【' + this.codeObj.testStripName + '】';
      } else {
        this.title = '编 辑【' + this.codeObj.testStripName + '】';
        this.isSubmitType = 'edit';
        this.isDisabled = true;

      }
    } else { // 新增
      this.currId = '';
      this.title = '新 增';
      this.isShowCodeMod = false;
      this.isSubmitType = 'add';
    }
  }
}
</script>
<style lang="scss" scoped>
.el-tooltip {
  span {
    padding-right: 10px;
  }
}

.w-100 {
  width: 100px;
}

.mb-20 {
  margin-bottom: 20px;
}

.mr-20 {
  margin-right: 20px;
}

/depp/ .el-upload-list {
  display: none;
}
</style>
